package com.bawei.module_main

import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.azhon.appupdate.manager.DownloadManager
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_storage.mmkv.AppMMKV
import com.bawei.module_main.databinding.ActivityMainBinding
import com.bawei.module_main.dialog.AppUpdateDialog
import com.bawei.module_main.ui.main.MainViewModel
import dagger.hilt.android.AndroidEntryPoint


const val TAG = "MainActivity"

@AndroidEntryPoint
@Route(path = Router.Ui.MainActivity)
class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_main

    override val mViewModel: MainViewModel by viewModels()

    private lateinit var mClubFragment: Fragment
    private lateinit var mMotoCircleFragment: Fragment
    private lateinit var mMallFragment: Fragment
    private lateinit var mMessageFragment: Fragment
    private lateinit var mMineFragment: Fragment

    companion object {
        private const val CLUB_FRAGMENT = "club"
        private const val MOTO_CIRCLE_FRAGMENT = "moto_circle"
        private const val MALL_FRAGMENT = "mall"
        private const val MESSAGE_FRAGMENT = "message"
        private const val MINE_FRAGMENT = "mine"
    }

    override fun initView() {
        mClubFragment = ARouter.getInstance().build(Router.Ui.ClubFragment).navigation() as Fragment
        mMotoCircleFragment =
            ARouter.getInstance().build(Router.Ui.MotoCircleFragment).navigation() as Fragment
        mMallFragment = ARouter.getInstance().build(Router.Ui.MallFragment).navigation() as Fragment
        mMessageFragment =
            ARouter.getInstance().build(Router.Ui.MessageFragment).navigation() as Fragment
        mMineFragment = ARouter.getInstance().build(Router.Ui.MineFragment).navigation() as Fragment
        navToFragment(R.id.nav_motor_circle)
        mBinding.navMotorCircle.isChecked = true
    }

    override fun initData() {
        mViewModel.checkUpdate()
    }

    override fun initListener() {
        //版本更新
        mViewModel.appUpdateLiveData_.observe(this) { updateModel ->
            if (updateModel != null) {
                if (updateModel.latestVersion.isEmpty() || updateModel.downloadUrl.isNullOrEmpty() || updateModel.latestVersion == "1.0.0") {
                    return@observe
                }
            }
            val new = updateModel.latestVersion.split(".")
            if (new.isEmpty() || new.size != 3) return@observe
            val current = "1.0.0".split(".")
            val newUpdate = isNeedUpdate(new, current)
            if (!newUpdate) return@observe
            if (updateModel.forceUpGrade != 2 || System.currentTimeMillis() - AppMMKV.lastLaunchTime > 10 * 60 * 1000L) {
                AppUpdateDialog(
                    title = String.format("最新版本%s升级说明", updateModel.latestVersion),
                    message = updateModel.message,
                    force = updateModel.forceUpGrade != 2,
                ) {
                    forceUpdate(updateModel!!.downloadUrl, updateModel.latestVersion)
                }.show(supportFragmentManager)
                AppMMKV.lastLaunchTime = System.currentTimeMillis()
            }
        }

        //点击切换底部导航
        mBinding.rgBottom.setOnCheckedChangeListener { _, i ->
            navToFragment(i)
        }
    }

    /**
     * 下载app并安装
     */
    private fun forceUpdate(downloadUrl: String, latestVersion: String) {
//        val manager = DownloadManager.Builder(this).run {
//            apkUrl(downloadUrl)
//            apkName("app_new_version.apk")
//                .enableLog(false)
//            smallIcon(R.mipmap.app_icon)
//            showBgdToast(true)
//            showNotification(true)
//            apkVersionName(latestVersion)
//            build()
//        }
//        manager.download()
    }

    private fun navToFragment(id: Int) {
        val bt = supportFragmentManager.beginTransaction()
        hideCurrentFragment(bt)
        when (id) {
            R.id.nav_motor_club -> {
                if (supportFragmentManager.findFragmentByTag(CLUB_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mClubFragment, CLUB_FRAGMENT)
                } else {
                    bt.show(mClubFragment)
                }
                bt.commitAllowingStateLoss()
            }

            R.id.nav_motor_circle -> {
                if (supportFragmentManager.findFragmentByTag(MOTO_CIRCLE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMotoCircleFragment, MOTO_CIRCLE_FRAGMENT)
                } else {
                    bt.show(mMotoCircleFragment)
                }
                bt.commitAllowingStateLoss()
            }

            R.id.nav_motor_mall -> {
                if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMallFragment, MALL_FRAGMENT)
                } else {
                    bt.show(mMallFragment)
                }
                bt.commitAllowingStateLoss()
            }

            R.id.nav_message -> {
                if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMessageFragment, MESSAGE_FRAGMENT)
                } else {
                    bt.show(mMessageFragment)
                }
                bt.commitAllowingStateLoss()
            }

            R.id.nav_mine -> {
                if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMineFragment, MINE_FRAGMENT)
                } else {
                    bt.show(mMineFragment)
                }
                bt.commitAllowingStateLoss()
            }
        }
    }

    private fun hideCurrentFragment(bt: FragmentTransaction) {
        if (supportFragmentManager.findFragmentByTag(MOTO_CIRCLE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMotoCircleFragment)
        }
        if (supportFragmentManager.findFragmentByTag(CLUB_FRAGMENT)?.isVisible == true) {
            bt.hide(mClubFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isVisible == true) {
            bt.hide(mMallFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMessageFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMineFragment)
        }
    }

    private fun isNeedUpdate(new: List<String>, current: List<String>): Boolean {
        if (new[0].toInt() > current[0].toInt()) {
            return true
        } else if (new[0].toInt() < current[0].toInt()) {
            return false
        }
        if (new[1].toInt() > current[1].toInt()) {
            return true
        } else if (new[1].toInt() < current[1].toInt()) {
            return false
        }
        if (new[2].toInt() > current[2].toInt()) {
            return true
        } else if (new[2].toInt() < current[2].toInt()) {
            return false
        }
        return false
    }


}